package jp.gr.jted.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import jp.gr.jted.bean.Language;
import jp.gr.jted.bean.Talk;

import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class TedUtil {

	private String talkListUrl = "http://www.ted.com/translate/languages/ja?page=";
	private String startWord = "	<a title=\"";

	private String talkDetailUrl = "http://www.ted.com";
	private String languageWord = "<select name=\"languageCode\" id=\"languageCode\"><option value=\"\">Show transcript</option>";

	private String subtitleUrl = "http://www.ted.com/talks/subtitles/id/@id@/lang/@lcid@/format/json";

	private String pageNumWord = "of <span class=\"notranslate nostyle\">";
	private int pageNum = 0;

	public ArrayList<Talk> getTalkList(int pageNum) throws HttpException, ClientProtocolException, IOException{

		ArrayList<Talk> talkList = new ArrayList<Talk>();

		// communicate TED Web site
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet method = new HttpGet(talkListUrl + pageNum);
		HttpResponse response = client.execute(method);
		int status = response.getStatusLine().getStatusCode();
		if (status != HttpStatus.SC_OK) throw new HttpException();

		// analyze the response
		HttpEntity entity = response.getEntity();
		InputStream is = null;
		BufferedReader in =null;
		try{
			is = entity.getContent();
			in = new BufferedReader(new InputStreamReader(is));
			String str;
			int start,end=0;
			while((str = in.readLine()) != null){
				if(str.startsWith(startWord)){
					Talk talk = new Talk();
					// title
					start = startWord.length();
					end = str.indexOf("\"",start);
					talk.setTitle(str.substring(start,end));
					// url
					start = str.indexOf("href=\"")+6;
					end = str.indexOf("\"",start);
					talk.setUrl(str.substring(start,end));
					// thumbnail
					start = str.lastIndexOf("src=\"")+5;
					end = str.indexOf("\"",start);
					talk.setThumbnail(str.substring(start,end));
					talkList.add(talk);
				}else if(str.indexOf(this.pageNumWord)>=0){
					start = str.indexOf(this.pageNumWord)+this.pageNumWord.length();
					end = str.indexOf("<",start);
					this.pageNum = Integer.parseInt(str.substring(start,end));
				}
			}
		}finally{
			if(in != null){
				try{
					in.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			if(is != null){
				try{
					is.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}

		return talkList;
	}

	public Talk getTalkDetail(String url) throws HttpException, ClientProtocolException, IOException{

		Talk talk = new Talk();

		// communicate TED Web site
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet method = new HttpGet(talkDetailUrl + url);
		HttpResponse response = client.execute(method);
		int status = response.getStatusLine().getStatusCode();
		if (status != HttpStatus.SC_OK) throw new HttpException();

		// analyze the response
		HttpEntity entity = response.getEntity();
		InputStream is = null;
		BufferedReader in =null;
		try{
			is = entity.getContent();
			in = new BufferedReader(new InputStreamReader(is));
			String str;
			int start,end=0;
			boolean languageFlag = false;
			ArrayList<Language> languageList = new ArrayList<Language>();
			talk.setLanguageList(languageList);
			while((str = in.readLine()) != null){
				if(languageFlag){
					if(str.startsWith("<option value=")){
						Language language = new Language();
						// lcid
						start = 15;
						end = str.indexOf("\"",start);
						language.setLcid(str.substring(start,end));
						// languageName
						start = str.indexOf(">") + 1;
						end = str.indexOf("<",start);
						language.setLanguageName(str.substring(start,end));
						languageList.add(language);
					}else{
						languageFlag = false;
					}
				}else{
					if(str.indexOf(this.languageWord)>=0){
						languageFlag = true;
						continue;
					}
					if(str.indexOf("data-id=")>=0){
						start = str.indexOf("data-id=") + 9;
						end = str.indexOf("\"",start);
						talk.setId(str.substring(start,end));
						break;
					}
				}
			}
		}finally{
			if(in != null){
				try{
					in.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			if(is != null){
				try{
					is.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}

		// getSubtitle
		talk.setFirstSubtitle(getSubtitle(talk.getId(),"en"));
		talk.setSecoundSubtitle(getSubtitle(talk.getId(),"ja"));

		return talk;
	}

	public String getSubtitle(String id,String lcid) throws HttpException, ClientProtocolException, IOException{

		StringBuffer subtitle = new StringBuffer();

		// communicate TED Web site
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet method = new HttpGet(this.subtitleUrl.replaceAll("@id@", id).replaceAll("@lcid@", lcid));
		HttpResponse response = client.execute(method);
		int status = response.getStatusLine().getStatusCode();
		if (status != HttpStatus.SC_OK) throw new HttpException();

		// analyze the response
		HttpEntity entity = response.getEntity();
		InputStream is = null;
		BufferedReader in =null;
		try{
			is = entity.getContent();
			in = new BufferedReader(new InputStreamReader(is));
			String str;
			while((str = in.readLine()) != null){
				subtitle.append(str);
			}
		}finally{
			if(in != null){
				try{
					in.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			if(is != null){
				try{
					is.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}

		return subtitle.toString();
	}

	public int getPageNum(){
		return this.pageNum;
	}
}
